<?php
Class UserDefinedFieldHelper extends AppHelper
{
	
	var $helpers = array('Form','Html','Javascript');
	function createField()
	{
		$script = $this->addCreateScript();
		$initialHtml = $this->initialHtml();
		$addLink = $this->Html->tag("div",$this->Html->link(__("Add Another Field"),"#",array("onclick"=>"return appendField(this)",'class'=>"addFieldButton")));
		$out = $this->Html->tag("div",$script.$initialHtml.$addLink,array('class'=>"user_field_template"));
		return $out;
	}
	
	function addCreateScript()
	{
		$template = str_replace("\n","",$this->input("{n}"));
		$js=<<<END
		<script type="text/javascript">
		var tempCount = 1;
		function appendField(caller)
		{
			var template = '$template';
			var out = 	template.replace(/{n}/g,tempCount);
			$(caller).parent().before(out);
			return false;
		}
		function removeField(obj)
		{
			\$(obj).parent().parent().css('display','none');
			console.log($(obj).parent().parent().find('input.deletedfield_flag').val(1));
			return false;
		}
		</script>	
END;
		return $js;
	}
	
	function initialHtml()
	{
		$formData = ClassRegistry::getObject('view')->data;
		$out  = '';
		if(isset($this->data['UserDefinedField'])&& is_array($this->data['UserDefinedField']))
		{
			foreach($this->data['UserDefinedField'] as $key =>$field)
			{
				$out .= $this->input($key);
			}
		}else
			$out = $this->input(0);
		return $out;
	}
	
	function input($key="{n}")
	{
		$out = $this->Form->input('UserDefinedField.'.$key.'.label',array('div'=>false,'type'=>"text"));
		$out  .= $this->Form->input('UserDefinedField.'.$key.'.value',array('div'=>false,'type'=>"text"));
		//for case if no user is field selected after remove
		$out  .= $this->Form->input('UserDefinedField.'.$key.'.deleted',array('div'=>false,'type'=>"text",'value'=>"0",'type'=>"text",'class'=>"deletedfield_flag",'style'=>"display:none",'label'=>false));
		$out .= $this->Html->tag('span',$this->Html->link(__("Remove"),"#",array("onclick"=>"return removeField(this)")));
		$out = $this->Html->tag('div',$out,array('id'=>"definedField_$key"));
		return $out;
	}
}
?>